package com.lemon.cloud.generator.web;

import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lemon.cloud.generator.entity.GenConfig;
import com.lemon.cloud.generator.entity.GenDatasourceConf;
import com.lemon.cloud.generator.service.GenDatasourceConfService;
import com.lemon.cloud.generator.service.GeneratorService;
import com.lemon.cloud.comm.model.ResultMsg;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 代码生成
 */
@RestController
@RequestMapping("/generator")
public class GeneratorController {

    @Autowired
    private GenDatasourceConfService datasourceConfService;

    @Autowired
    private GeneratorService generatorService;

    /**
     * 查询数据源的表，默认是当前数据库
     *
     * @param page
     * @param tableName
     * @param dsName
     * @return
     */
    @GetMapping("/page")
    public ResultMsg<IPage<List<Map<String, Object>>>> getPage(Page<GenDatasourceConf> page, String tableName, String dsName) {
        return ResultMsg.resultSuccess(datasourceConfService.getPage(page, tableName, dsName));
    }

    @PostMapping("/code")
    @SneakyThrows
    public void generateCode(@RequestBody GenConfig genConfig, HttpServletResponse response) {
        byte[] data = generatorService.generatorCode(genConfig);
        response.reset();
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                String.format("attachment; filename=%s.zip", genConfig.getTableName()));
        response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
        response.setContentType("application/octet-stream; charset=UTF-8");

        IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
    }

    /**
     * 预览代码
     * @param genConfig 数据表配置
     * @return
     */
    @GetMapping("/preview")
    public ResultMsg<Map<String, String>> previewCode(GenConfig genConfig) {
        return ResultMsg.resultSuccess(generatorService.previewCode(genConfig));
    }
}
